<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./fonticon/style.css">
    <link rel="stylesheet" href="./image_preview.css">
</head>
<body class="">
<header class="header">
    <button class="icon-circle-close close-window" onclick="winClose()"></button>
</header>

<div class="img-container" onmousewheel="wheelScaleImage(event)">
    <div class="img-wrapper" id="imgWraper" onmousedown="startMouseMove(event);">
        <img src="" onload="imageOnLoad()" alt="">
    </div>
</div>

<!-- 上一张下一张 -->
<button class="icon-prev visible-hidden" onclick="nextImage(-1);" title="上一张"></button>
<button class="icon-next visible-hidden" onclick="nextImage(1);" title="下一张"></button>

<div class="img-operations">
    <div class="operations-btns">
        <button class="icon-zoom-in" title="放大" onclick="scaleImage(0.1)"></button>
        <button class="icon-zoom-out" title="缩小" onclick="scaleImage(-0.1)"></button>
        <button class="icon-rotate" title="旋转" onclick="rotateImage()"></button>
        <button class="icon-download hidden" title="下载" onclick="downloadImage()"></button>
        <button class="icon-star hidden" title="收藏" onclick="favorImage()"></button>
    </div>
</div>
<div id="waterMask"></div>

<div id="messageContainer" class="message-container">

</div>

<script>

    if (window.navigator.userAgent.indexOf('Mac') > -1) {
        document.body.classList.add('mac-os');
    } else {
        document.body.classList.add('windows-os');
    }
    /* disable contextmenu */
    document.oncontextmenu = function () {
        return false;
    };

    /* 图片是否收藏 */
    function isImageInCollection(imageItem) {
        var currentUser = JSON.parse(localStorage.getItem("CURRENT_USER")) || {};
        var customEmoticon = JSON.parse(localStorage.getItem("CUSTOM_EMOTICON")) || {};

        var result;
        if (!currentUser || !customEmoticon) {
            result = false;
        } else {
            var currentUserCustomEmoticon = customEmoticon[currentUser['user_id']] || [];
            result = currentUserCustomEmoticon.filter(function(elem) {
                return imageItem.mediaId === elem.mediaId;
            }).length > 0;
        }
        if (result) {
            document.querySelector(".icon-star").classList.add("incollect");
        } else {
            document.querySelector(".icon-star").classList.remove("incollect");
        }

        return result;
    }

    /* 更新收藏状态 */
    window.addEventListener("storage", function (e) {
        isImageInCollection(images[index]);
    });

    /* 图片操作初始化数据 */
    var scale = 1,
            rotate = 0,
            mainImage = document.querySelector(".img-wrapper img"),
            imgStyle = mainImage.style,
            imageWraper = document.querySelector("#imgWraper"),
            wraperStyle =  imageWraper.style,
            images = window.opener.imagePreview.images,
            imageConfig = window.opener.imagePreview.options;
    isFirstShow = true,
            nwjsWin = require('nw.gui').Window.get(),
            message = document.querySelector("#messageContainer"),
            index = images.indexOf(images.filter(function(i){
                return window.opener.imagePreview.currentImage.deliveryId == i.deliveryId;
            })[0]);
            // nwjsWin.showDevTools();
    /* 水印 */
    document.querySelector("#waterMask").style.backgroundImage = 'url(' + imageConfig.watermarkConfig.watermarkBgUrl + ')';
    if (imageConfig.readOnly) {
        document.querySelector(".icon-download").style.display = "none";
    } else {
        document.querySelector(".icon-download").style.display = "inline";
    }

    // 设置不能收藏图片
    imageConfig.enableStar = false;
    if (imageConfig.enableStar) {
        document.querySelector(".icon-star").style.display = "inline";
    } else {
        document.querySelector(".icon-star").style.display = "none";
    }

    function winClose(){
        nwjsWin.close();
    }
    
    mainImage.addEventListener('error', function (evt) {
        document.querySelector(".img-container").classList.remove("loading");

        if (this.getAttribute('src') !== '') {
            createMessage("warning", "获取图片失败，请稍后重试!");
        }
    });

    /* 图片加载效果 */
    function imageOnLoad(){
        var winHeight, winWidth, isMaxHeight = false, isMaxWidth = false;

        /* 第一次打开窗口尽量适应图片 */
        if(isFirstShow){
            isFirstShow = false;

            if(window.screen.width<mainImage.naturalHeight){
                isMaxHeight  = true;
                winHeight = window.screen.height;
            } else {
                winHeight = mainImage.naturalHeight;
            }

            if(window.screen.width-300<mainImage.naturalWidth){
                isMaxWidth = true;
                winWidth = window.screen.width-300;
            } else {
                winWidth = mainImage.naturalWidth;
            }

            if(winHeight<400){
                winHeight = 400;
            }

            if(winWidth<600){
                winWidth = 600;
            }

            /* 窗口尺寸尽量和图片比例保持一致 (过大，过小不能保证比例一致)*/
            if(mainImage.naturalHeight > mainImage.naturalWidth){
                var w = winHeight*mainImage.naturalWidth/mainImage.naturalHeight;
                if(!(isMaxWidth && w>winWidth)){ //允许再放大
                    winWidth = w;
                }
            } else if(mainImage.naturalHeight <= mainImage.naturalWidth){
                var h = mainImage.naturalHeight/mainImage.naturalWidth*winWidth; //预留出上下工具栏的空间
                if(!(isMaxHeight && h>winHeight)){ //允许再放大
                    winHeight = h;
                }
            }

            if(winHeight<400){
                winHeight = 400;
            } else if(winHeight>window.screen.height-200){
                winHeight = window.screen.height-200;
            }

            if(winWidth<600){
                winWidth = 600;
            } else if(winWidth>window.screen.width-200){
                winWidth = window.screen.width-200;
            }

            winHeight += 100; //上下工具栏

            /* 窗体的原始尺寸被改变 */
            //if(winHeight!=400 || winWidth!=600){
            //nwjsWin.resizeTo(Math.round(winWidth), Math.round(winHeight));
            console.log(Math.round((window.screen.width-winWidth)/2), Math.round((window.screen.height-winHeight)/2));
            console.log(winWidth, winHeight);
            /* 窗口居中 */
            //nwjsWin.moveTo(Math.round((window.screen.width-winWidth)/2), Math.round((window.screen.height-winHeight)/2));
            //}
        } else {
            winHeight = nwjsWin.height;
            winWidth = nwjsWin.width;
        }

        var height, width;
        if(mainImage.naturalHeight>winHeight){
            height = winHeight-100; //预留出上下工具栏的空间
        } else {
            height = mainImage.naturalHeight;
        }

        if(mainImage.naturalWidth>winWidth){
            width = winWidth-100; //预留出上下工具栏的空间
        } else {
            width = mainImage.naturalWidth;
        }

        /* 回放到自然比例 */
        if((height/width) != (mainImage.naturalHeight/mainImage.naturalWidth)){
            if(mainImage.naturalHeight > mainImage.naturalWidth || isMaxHeight){
                width = height*mainImage.naturalWidth/mainImage.naturalHeight;
            } else if(mainImage.naturalHeight <= mainImage.naturalWidth && !isMaxHeight){
                height = mainImage.naturalHeight/mainImage.naturalWidth*width;
            }
        }

        wraperStyle.height = height + 'px';
        wraperStyle.width = width + 'px';

        document.querySelector(".img-container").classList.remove("loading");
    }

    /* 上一张下一张 */
    function nextImage(i){
        index+=i;

        if(index<0){
            index = 0;
            return;
        } else if(index>=images.length){
            index = images.length-1;
            return;
        }

        document.querySelector(".img-container").classList.add("loading");
        scale = 1;
        rotate = 0;

        if(index==0){
            document.querySelector(".icon-prev").style.display = "none";
        } else {
            document.querySelector(".icon-prev").style.display = "block";
        }

        if(index == images.length-1){
            document.querySelector(".icon-next").style.display = "none";
        } else {
            document.querySelector(".icon-next").style.display = "block";
        }

        /* 还原 */
        imageWraper.classList.remove("free_move");
        wraperStyle.top = null;
        wraperStyle.left = null;
        wraperStyle.transform = null;

        var imgData = images[index];

        isImageInCollection(imgData);
        mainImage.src = imgData.mediaUrl;
    }
    /* 显示第一张图片 */
    nextImage(0);

    /* 缩放图片 */
    function scaleImage(s){
        if(!imageWraper.classList.contains("free_move")){
            var rect = imageWraper.getBoundingClientRect();
            imageWraper.classList.add("free_move");
            wraperStyle.top = rect.top + 'px';
            wraperStyle.left = rect.left + 'px';
        }

        /* 	var rect = imageWraper.getBoundingClientRect();
         if(s<0 && !(rect.height>100 || rect.height>100)){
         console.log(mainImage.naturalHeight, mainImage.naturalWidth)
         if((mainImage.naturalHeight>100 || mainImage.naturalWidth>100)){
         return;
         } else if(rect.height<=mainImage.naturalHeight || rect.width<=mainImage.naturalWidth) {
         return;
         }
         } */
        scale+=s;

        if (scale < 0.1) {
            scale = 0.1;
        }
        wraperStyle.transform = 'rotate(' + rotate + 'deg) scale(' + scale + ')';
    }

    /* 旋转图片 */
    function rotateImage(){
        rotate += 90;
        wraperStyle.transform = 'rotate(' + rotate + 'deg) scale(' + scale + ')';
    }

    /*  */
    var fs = require("fs");
    var path = require("path");

    function getDownloadPath() {
        var currentUser = JSON.parse(localStorage.getItem('CURRENT_USER'));
        var lastTimeDownloadPath = JSON.parse(localStorage.getItem('LAST_TIME_DOWNLOAD_PATH')) || {};

        if (!currentUser) { return ''; }
        lastTimeDownloadPath = lastTimeDownloadPath[currentUser.user_id] || (path.join(process.env.USERPROFILE || process.env.HOMEPATH || process.env.HOME, 'Documents\\'));
        if (lastTimeDownloadPath.lastIndexOf(path.sep) !== lastTimeDownloadPath.length - 1) {
            lastTimeDownloadPath = lastTimeDownloadPath.substring(0, lastTimeDownloadPath.lastIndexOf(path.sep) + 1);
        }
console.log(`lastTimeDownloadPath:`, lastTimeDownloadPath);
        return lastTimeDownloadPath;
    }

    message.addEventListener("transitionend", function(e){
        message.removeChild(e.target);
    });

    /* 创建提示信息 */
    function createMessage(type, text){
        var msg = document.createElement("div");
        msg.innerText = text;
        message.appendChild(msg);

        msg.classList.add("message");
        msg.classList.add('icon-' + type);
        setTimeout(function(){
            msg.classList.add("dying-message");
        }, 10);
    }

    /* 下载图片 */
    function downloadFile(mediaUrl, filePath) {
        var file = fs.createWriteStream(filePath);
        var http;
        /* http or https */
        if (imageConfig.isHttps) {
            http = require('https');
        } else {
            http = require('http');
        }

        var req = http.get(mediaUrl, function (res) {
            if (res.statusCode !== 200) {
                createMessage("warning", "网络错误");
            } else {
                res.pipe(file);
            }

            res.on('data', function (chunk) {
            }).on('end', function (data) {
                createMessage("success", "下载成功");
            }).on('error', function (err) {
                createMessage("warning", "下载失败");
            });
        });
    }

    function getFileName(image) {
        return image.isGif ? (image.deliveryId + '.gif') : (image.deliveryId + '.png');
    }

    /* 下载图片 */
    function downloadImage(){
        var currentImage = images[index];
        var mediaUrl = currentImage.mediaUrl;

        var $downloadFile = document.querySelector('#downloadFile');
        if($downloadFile){
            $downloadFile.parentNode.removeChild($downloadFile);
        }

        $downloadFile = document.createElement('input');
        document.body.appendChild($downloadFile);


        $downloadFile.setAttribute('id', "downloadFile");
        $downloadFile.setAttribute('type', "file");
        $downloadFile.setAttribute('accept', currentImage.isGif ? '.gif' : '.png');
        $downloadFile.setAttribute('nwsaveas', path.resolve(getDownloadPath(), getFileName(currentImage)));

        $downloadFile.onchange = function (evt) {
            var mediaUrl = currentImage.mediaUrl;
            var filePath = this.value;
            downloadFile(mediaUrl, filePath);
        };

        $downloadFile.click();
    }

    /* 收藏图标 */
    function favorImage(){
        var currentImage = images[index];
        var currentUser = JSON.parse(localStorage.getItem("CURRENT_USER"));
        var customEmoticon = JSON.parse(localStorage.getItem("CUSTOM_EMOTICON")) || {};

        if (!currentUser) {
            console.log('Get current user info error');
            return false;
        }

        var currentUserId = currentUser['user_id'];
        var currentUserCustomEmoticon = customEmoticon[currentUserId] || [];

        if (isImageInCollection(currentImage)) {
            var index2 = currentUserCustomEmoticon.indexOf(currentUserCustomEmoticon.filter(function(elem) {
                return elem.mediaId === currentImage.mediaId;
            })[0]);
            currentUserCustomEmoticon.splice(index2, 1);
        } else {
            currentUserCustomEmoticon.push({
                mediaId: currentImage.mediaId,
                isGif: currentImage.isGif,
                width: currentImage.width,
                height: currentImage.height
            });
        }
        customEmoticon[currentUserId] = currentUserCustomEmoticon;
        localStorage.setItem("CUSTOM_EMOTICON", JSON.stringify(customEmoticon));
        isImageInCollection(currentImage);
    }

    /* 图片移动 */
    var startXY,
            mouseMove = function(e){
                var top = startXY.top+e.clientY-startXY.y;
                var left = startXY.left+e.clientX-startXY.x;
        wraperStyle.top = top + 'px';
        wraperStyle.left = left + 'px';
    };

    function startMouseMove(e) {
        /* 没有移动过 */
        if(!imageWraper.classList.contains("free_move")){
            var rect = imageWraper.getBoundingClientRect();
            startXY = {
                x: e.clientX,
                y: e.clientY,
                top: rect.top,
                left: rect.left
            }
            imageWraper.classList.add("free_move");
            wraperStyle.top = rect.top + 'px';
            wraperStyle.left = rect.left + 'px';
        } else {
            startXY = {
                x: e.clientX,
                y: e.clientY,
                top: parseInt(wraperStyle.top),
                left: parseInt(wraperStyle.left)
            }
        }

        document.querySelector(".img-container").addEventListener("mousemove", mouseMove);
    }

    /* 取消移动 */
    document.addEventListener("mouseup", function(e){
        document.querySelector(".img-container").removeEventListener("mousemove", mouseMove);
    });

    function wheelScaleImage(e) {
        console.info(`wheelDelta:`, e.wheelDelta);
        scaleImage((e.wheelDelta / 1200)*1);
        //nextImage(e.wheelDelta>0?1:-1);
    };

</script>
</body>
</html>
